#include "MonitoringWarnRecode.h"
#include "ui_MonitoringWarnRecode.h"
#include "SnaillTcpClient.h"
#include <QJsonArray>
MonitoringWarnRecode::MonitoringWarnRecode(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MonitoringWarnRecode),
    devmodel(this)
{
    ui->setupUi(this);
    ui->tableView->setModel(&devmodel);


    connect(SnaillTcpClient::instance(), &SnaillTcpClient::dataReceived, this, &MonitoringWarnRecode::handleDataReceived);
    LOG_INFO("查看警告记录");
}

MonitoringWarnRecode::~MonitoringWarnRecode()
{
    delete ui;

}

QList<wareRecodeModel> MonitoringWarnRecode::getRecodeList(const QString &jsonString)
{
    QList<wareRecodeModel> recodeList;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
    if (jsonDoc.isObject()) {
        QJsonObject rootObject = jsonDoc.object();
        if (rootObject.contains("data") && rootObject["data"].isArray()) {
            QJsonArray jsonArray = rootObject["data"].toArray();
            for (const QJsonValue &value : jsonArray) {
                if (value.isObject()) {
                    QJsonObject deviceObject = value.toObject();
                    wareRecodeModel recode;
                    recode.id = deviceObject["id"].toString();
                    recode.device_id = deviceObject["device_id"].toString();
                    recode.timestamp = deviceObject["timestamp"].toString();
                    recode.content = deviceObject["content"].toString();
                    recode.status = deviceObject["status"].toString();
                    recode.note = deviceObject["note"].toString();
                    recodeList.append(recode);
                }
            }
        }
    }
    return recodeList;
}

void MonitoringWarnRecode::handleDataReceived(const QByteArray &data)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    QJsonObject jsonObj = jsonDoc.object();
    QString action = jsonObj["action"].toString();
    if(action=="getwarnrecode"){
        qDebug()<<"getwarnrecode==="<<jsonObj;

        recodeList =getRecodeList(data);
        devmodel.updateAllDeviceList(recodeList);
    }else if (action=="deviceDelete") {

    }
}

void MonitoringWarnRecode::showEvent(QShowEvent *event)
{
    qDebug() << "页面显示，进入页面操作可在此处添加";
    QJsonObject jsonObj;
    jsonObj["action"] ="getwarnrecode";
    if (SnaillTcpClient::instance()->sendJsonData(jsonObj)) {
        //  qDebug() << "deviceList data sent successfully";
    } else {

        return ;
    }
    QWidget::showEvent(event);
}
